<template>
  <div class="article-list" ref="article-list">
    <van-pull-refresh
      v-model="isRefreshLoading"
      :success-text="refreshSuccessText"
      :success-duration="1500"
      @refresh="onRefresh" >
      <van-list finished-text="没有更多了" >
        <article-item
          v-for="(article, index) in articles"
          :key="index"
          :article="article" />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from '@/components/article-item.vue'
import { debounce } from 'lodash'
export default {
  components: {
    ArticleItem
  },
  props: {},
  data () {
    return {
      articles: [],
      finished: false, // 加载结束不再触发加载更多
      timestamp: 1, // 下一页页码
      isRefreshLoading: false, // 下拉刷新的状态
      refreshSuccessText: '', // 下拉刷新成功的提示文本
      scrollTop: 0 // 列表滚动到顶部的距离
    }
  },
  computed: {},
  watch: {},
  mounted () {
    this.onLoad(1)
    const articleList = this.$refs['article-list']
    articleList.onscroll = debounce(() => {
      this.scrollTop = articleList.scrollTop
    }, 50)
  },
  activated () {
    this.$refs['article-list'].scrollTop = this.scrollTop
  },
  methods: {
    onLoad: debounce(function (page) {
      this.$http('api/tableTest/page', {
        params: {
          page: page || this.timestamp,
          limit: 10 * this.timestamp
        }
      }).then(({ data: res }) => {
        if (res.code === 0) {
          if (res.total === this.articles.length) {
            this.finished = true
          } else {
            this.timestamp++
            this.articles = res.data
          }
        }
      })
    }, 800, { leading: true, trailing: false }),

    onRefresh () {
      this.onLoad(1)
      this.isRefreshLoading = false
    }
  }
}
</script>

<style scoped lang="less">
.article-list {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 50px;
  top: 50px;
  overflow-y: auto;
}
</style>
